<template>
  <div class="register">
    <el-dialog :visible.sync="dialogFormVisible" width="600px" :show-close="false" :center="true">
      <div slot="title" class="title">用户注册</div>

      <el-form :model="form" label-width="66px" :rules="rules" ref="form">
        <el-form-item label="头像" prop="avatar">
          <el-upload
            class="avatar-uploader"
            :show-file-list="false"
            :action="baseUrl+'/uploads'"
            name="image"
            :on-success="handleAvatarSuccess"
            :before-upload="beforeAvatarUpload"
          >
            <img v-if="imageUrl" :src="imageUrl" />
            <i v-else class="el-icon-plus avatar-uploader-icon"></i>
          </el-upload>
        </el-form-item>

        <el-form-item label="昵称" prop="username">
          <el-input v-model="form.username"></el-input>
        </el-form-item>

        <el-form-item label="邮箱" prop="email">
          <el-input v-model="form.email"></el-input>
        </el-form-item>

        <el-form-item label="手机" prop="phone">
          <el-input v-model="form.phone"></el-input>
        </el-form-item>

        <el-form-item label="密码" prop="password">
          <el-input v-model="form.password" show-password></el-input>
        </el-form-item>

        <el-form-item label="图形码" prop="code">
          <el-row>
            <el-col :span="16">
              <el-input v-model="form.code"></el-input>
            </el-col>
            <el-col :span="7" :offset="1">
              <img :src="codeUrl" class="code-img" alt @click="refreshCode" />
            </el-col>
          </el-row>
        </el-form-item>

        <el-form-item label="验证码" prop="rcode">
          <el-row>
            <el-col :span="16">
              <el-input v-model="form.rcode"></el-input>
            </el-col>
            <el-col :span="7" :offset="1">
              <el-button @click="getRcode" :disabled="timeout<60 && timeout>0">
                获取用户验证码
                <span v-if="timeout<60 && timeout>0">{{timeout}}</span>
              </el-button>
            </el-col>
          </el-row>
        </el-form-item>
      </el-form>

      <div slot="footer">
        <el-button @click="dialogFormVisible = false">取 消</el-button>
        <el-button type="primary" @click="submit">确 定</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
// import instance from "@/utils/request.js";
import { getPhoneCode, register } from '@/api/register.js'
var timer = null
export default {
  data() {
    return {
      dialogFormVisible: false,
      timeout: 60,
      form: {
        avatar: "",
        username: "",
        email: "",
        phone: "",
        password: "",
        code: "",
        rcode: ""
      },
      baseUrl: process.env.VUE_APP_URL,
      imageUrl: "",
      codeUrl: process.env.VUE_APP_URL + "/captcha?type=sendsms",
      rules: {
        avatar: [
          { required: true, message: "请选择头像上传", trigger: "change" }
        ],
        username: [
          { required: true, message: "请输入昵称", trigger: "change" }
        ],
        email: [
          { required: true, message: "请输入邮箱地址", trigger: "change" },
          // 自定义校验规则
          {
            validator: (rule, value, callback) => {
              let _reg = /\w+([-+.]\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*/;
              if (_reg.test(value)) {
                callback();
              } else {
                callback("请正确输入邮箱地址");
              }
            },
            trigger: "change"
          }
        ],
        phone: [
          { required: true, message: "请输入手机号码", trigger: "change" },
          { min: 11, max: 11, message: "号码长度为11位", trigger: "change" },
          // 自定义手机号验证规则
          {
            validator: (rule, value, callback) => {
              let _reg = /^(0|86|17951)?(13[0-9]|15[012356789]|166|17[3678]|18[0-9]|14[57])[0-9]{8}$/;
              if (_reg.test(value)) {
                callback();
              } else {
                callback("手机号码格式不正确");
              }
            },
            trigger: "change"
          }
        ],
        password: [
          { required: true, message: "请填写密码", trigger: "change" },
          {
            min: 6,
            max: 12,
            message: "密码长度应为6-12位长度",
            trigger: "change"
          }
        ],
        code: [
          { required: true, message: "请填写图形码", trigger: "change" },
          { min: 4, max: 4, message: "长度为4位字符", trigger: "change" }
        ],
        rcode: [
          { required: true, message: "请填写短信验证码", trigger: "change" },
          { min: 4, max: 4, message: "验证码长度为4位字符", trigger: "change" }
        ]
      }
    };
  },

  methods: {
    handleAvatarSuccess(res) {
      // this.imageUrl = URL.createObjectURL(file.raw);
      // console.log(res);
      this.imageUrl = this.baseUrl + "/" + res.data.file_path;
      this.form.avatar = res.data.file_path;
      // 对头像进项验证
      this.$refs.form.validateField("avatar", err => {
        if (err) {
          console.log("报错");
        }
      });
    },

    beforeAvatarUpload(file) {
      const isJPG = file.type === "image/jpeg" || file.type === "image/png";
      const isLt2M = file.size / 1024 / 1024 < 2;

      if (!isJPG) {
        this.$message.error("上传头像图片只能是 JPG 格式!");
      }
      if (!isLt2M) {
        this.$message.error("上传头像图片大小不能超过 2MB!");
      }
      return isJPG && isLt2M;
    },

    refreshCode() {
      this.codeUrl = this.baseUrl + "/captcha?type=sendsms&xxx=" + Date.now();
    },

    submit() {
      this.$refs.form.validate(result => {
        if (!result) {
          this.$message.warning("注册不成功,请重新填写信息");
        } else {
          // 调用注册接口
          register(this.form).then(() => {
            // if(res.code == 200){
              this.$message.success('注册成功')
              this.dialogFormVisible = false
            // } else {
              // this.$message.warning(res.message)
            // }
          });
        }
      });
    },

    // 获取用户验证码
    getRcode() {
      // 设置一个变量表示 手机号和图形码规则的验证结果
      let _isPass = true;
      // 验证手机号与图形码的规则
      this.$refs.form.validateField(["code", "phone"], err => {
        // 有一个没通过验证，则为false
        if (err) {
          _isPass = false;
        }
      });

      if (_isPass == false) {
        return;
      } else {
        this.timeout--;
        // 定时器
        timer = setInterval(() => {
          this.timeout--;
          if (this.timeout == 0) {
            this.timeout = 60;
            // 清除定时器
            clearInterval(timer);
          }
        }, 1000);

      }

      getPhoneCode({
        code: this.form.code,
        phone: this.form.phone
      }).then(res => {
        // console.log(res);        
        if(res.code == 200){
          this.$message.success("短信验证码为:" + res.data.captcha);
        }else{
          this.refreshCode()
        }
      });
    }
  },

  // 关闭页面时，清空表单
  watch: {
    'dialogFormVisible' (value){
      if(value == false){
        this.$refs.form.resetFields()
        this.imageUrl = ''
        this.timeout = 60
        clearInterval(timer)
      }
    }
  },
};
</script>

<style lang="less">
.register {
  .el-dialog__header {
    padding: 0;
  }

  .title {
    width: 600px;
    height: 53px;
    background: linear-gradient(to right, #01c5fa, #1394fa);
    line-height: 53px;
    color: #fff;
  }

  .el-input__inner {
    height: 39px;
  }

  .code-img {
    width: 100%;
    height: 39px;
  }

  .avatar-uploader {
    text-align: center;
  }

  .avatar-uploader .el-upload {
    border: 1px dashed #d9d9d9;
    border-radius: 6px;
    cursor: pointer;
    position: relative;
    overflow: hidden;
  }

  .avatar-uploader .el-upload:hover {
    border-color: #409eff;
  }

  .el-upload.el-upload--text {
    width: 178px;
    height: 178px;

    img {
      width: 100%;
    }
  }

  .avatar-uploader-icon {
    font-size: 28px;
    color: #8c939d;
    width: 178px;
    height: 178px;
    line-height: 178px;
    text-align: center;
  }
  .avatar {
    width: 178px;
    height: 178px;
    display: block;
  }
}
</style>